let fn_list = async (ctx, next) => {
   
    let keyword = ctx.request.query.keyword || '';
    console.log(keyword.length);
    if (keyword) {
        let list;

        list = await Bolgs.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { headline: keyword },
                    { abstract: keyword },
                    { content: keyword },
                    { classify: keyword },
                    { author: keyword },
                ]
            },
            order:['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求成功'
        }
    } else {
        let list = await Bolgs.findAll({
            order:['id']
        });
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求成功'
        }
    }
}
let fn_getbyid = async (ctx, next) => {
    let id = ctx.request.params.id;
    let bolg = await Bolgs.findByPk(id);
    if (bolg) {
        ctx.body = {
            code: 1000,
            data: bolg,
            msg: '获取博客成功'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '你查找的博客不存在'
        }
    }
}
let fn_post =async (ctx, next) => {
    let obj = ctx.request.body;
    console.log(obj);

    await Bolgs.create(obj);
    ctx.body = obj;
}
let fn_put =async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let bolg = await Bolgs.findByPk(id);
    if (bolg) {
        Bolgs.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: bolg,
            msg: '修改成功'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '你修改的博客不存在'
        }
    }
}
let fn_delete =async (ctx, next) => {

    let id = ctx.request.params.id;
    console.log(id);
    let bolg = await Bolgs.findByPk(id);
    if (bolg) {
        Bolgs.destroy({
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id },
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '要删除的记录不存在'
        }
    }
}

module.exports = {
    'get /bolg': fn_list,
    'get /bolg/:id': fn_getbyid,
    'post /bolg': fn_post,
    'put /bolg/:id': fn_put,
    'delete /bolg/:id': fn_delete
}